<?php
namespace app\pic\admin;
use app\system\admin\Admin;
use think\Db;
class Authors extends Admin
{
    protected $hisiModel = '';//模型名称[通用添加、修改专用]
    protected $hisiTable = 'users';//表名称[通用添加、修改专用]
    protected $hisiAddScene = '';//添加数据验证场景名
    protected $hisiEditScene = '';//更新数据验证场景名

    public function index()
    {
        if($this->request->isAjax()){
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 15);
            $model = Db::name('users')->alias('u');
            $where = [];
            $where['u.user_type'] = 1;
            $where['a.identity_type'] = 'username';
            $field = 'u.*,a.id as aid,identifier,createtime';
            $data['data'] = $model->join('user_auths a', 'u.id=a.user_id')
                            ->field($field)->where($where)
                            ->page($page)->limit($limit)
                            ->select();
            $data['count'] = $model->where($where)->count('u.id');
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }

        return $this->fetch();
    }

    public function add() {
		if($this->request->isPost()){
			$model = Db::name('users');
			$data = $this->request->param();
            $data = array_map('trim', $data);
            $checkUsername = checkUserName($data['identifier']);
            if($checkUsername['errcode'] != 0){
                // exit(exitJson($checkUsername['errcode'], $checkUsername['errmsg']));
                return $this->error($checkUsername['errmsg']);
            }
            if($data['password'] != $data['repasswd']){
                return $this->error('两次密码输入不一致!');
                // exit(exitJson(1, '两次密码输入不一致!'));
            }
            Db::startTrans();
            try {
                $find = Db::name('user_auths')->where('identity_type','username')->where('identifier',$data['identifier'])->find();
                if($find){
                    throw new Exception("账号已存在", 1);
                }
                $insert_data = [
                    'nickname' => $data['nickname'],
                    'avatar'   => '/static/images/avatar.png',
                    'user_type'=> 1,
                    'createtime'=> date('Y-m-d H:i:s',time())
                ];
                $insertId = $model->insertGetId($insert_data);
                if($insertId > 0){
                    $auth_data = [
                        'user_id' => $insertId,
                        'identity_type' => 'username',
                        'identifier'    => $data['identifier'],
                        'credential'    => password_hash($data['password'],1)
                    ];

                    Db::name('user_auths')->insert($auth_data);
                }else{
                    throw new Exception("添加失败", 1);

                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                return $this->error($e->getMessage());
            }
            return $this->success('添加成功!');

		}

		return $this->fetch('form');

    }


    public function edit() {
		if($this->request->isPost()){
			$model = Db::name('users');
			$data = $this->request->param();
            $data = array_map('trim', $data);

            $checkUsername = checkUserName($data['identifier']);
            if($checkUsername['errcode'] != 0){
                return $this->error($checkUsername['errmsg']);
                // exit(exitJson($checkUsername['errcode'], $checkUsername['errmsg']));
            }

            if(!empty($data['password']) && $data['password'] != $data['repasswd']){
                return $this->error('两次密码输入不一致!');
                // exit(exitJson(1, '两次密码输入不一致!'));
            }

            Db::startTrans();
            try {
                $update_data = [
                    'nickname' => $data['nickname'],
                ];
                $model->where('id',$data['id'])->update($update_data);
                if(!empty($data['password'])){
                    $auth_data = [
                        'identifier'    => $data['identifier'],
                        'credential'    => password_hash($data['password'],1)
                    ];
                }else{
                    $auth_data = [
                        'identifier'    => $data['identifier'],
                    ];
                }
                Db::name('user_auths')->where('user_id',$data['id'])->where('identity_type','username')->update($auth_data);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                return $this->error($e->getMessage());
                // exit(exitJson(2, $e->getMessage()));
            }
            return $this->success('修改成功!');
			exit(exitJson(0, '修改成功!'));
		}
        $id = $this->request->param('id');
        $field = 'u.*,ua.id as aid,identifier,createtime';
        $model = Db::name('users')->alias('u');
        $formData = $model->join('user_auths ua', 'u.id=ua.user_id')->field($field)->where('u.id',$id)->find();
        $this->assign('formData', $formData);
        return $this->fetch('form');

    }
}
